package org.sky.axis2.attachment;

import java.io.File;
import java.io.FileOutputStream;

import javax.activation.DataHandler;

import org.apache.axiom.attachments.Attachments;
import org.apache.axis2.context.MessageContext;
import org.sky.axis2.util.UUID;

public class FileUploadService {
	public String uploadFile(String name, String attchmentID) throws Exception {
		FileOutputStream fileOutputStream = null;
		StringBuffer uploadFilePath = new StringBuffer();
		String fileNamePrefix = "";
		String fileName = "";
		try {
			MessageContext msgCtx = MessageContext.getCurrentMessageContext();
			Attachments attachment = msgCtx.getAttachmentMap();
			DataHandler dataHandler = attachment.getDataHandler(attchmentID);
			fileNamePrefix = name.substring(name.indexOf("."), name.length());
			fileName = UUID.getUUID();
			System.out.println("fileName=====" + fileName);
			System.out.println("fileNamePrefix====" + fileNamePrefix);
			uploadFilePath.append("D:/upload/axis2/");
			uploadFilePath.append(fileName);
			uploadFilePath.append(fileNamePrefix);
			System.out
					.println("uploadFilePath====" + uploadFilePath.toString());
			File file = new File(uploadFilePath.toString());
			fileOutputStream = new FileOutputStream(file);
			dataHandler.writeTo(fileOutputStream);
			fileOutputStream.flush();
		} catch (Exception e) {
			throw new Exception(e);
		} finally {
			try {
				if (fileOutputStream != null) {
					fileOutputStream.close();
					fileOutputStream = null;
				}
			} catch (Exception e) {
			}
		}
		return "File saved succesfully.";
	}
}